/*

 * Copyright (C) 2021 Huawei Device Co., Ltd.

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
package com.ubhave.sensormanager.ability;

import com.ubhave.sensormanager.ESException;
import com.ubhave.sensormanager.ESSensorManager;
import com.ubhave.sensormanager.ResourceTable;
import com.ubhave.sensormanager.SensorDataListener;
import com.ubhave.sensormanager.data.SensorData;
import com.ubhave.sensormanager.data.env.AmbientTemperatureData;
import com.ubhave.sensormanager.data.env.MagneticFieldData;
import com.ubhave.sensormanager.sensors.SensorUtils;
import com.ubhave.sensormanager.utils.LogUtil;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.bundle.IBundleManager;
import ohos.security.SystemPermission;
import ohos.utils.PacMap;
import ohos.utils.Sequenceable;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Optional;

public class MagneticFieldAbility  extends Ability implements Component.ClickedListener, SensorDataListener {
    private Button startBtn;
    private Button stopBtn;
    private Text temperatureData;
    private ESSensorManager sensorManager;
    private int subscriptionId;
    private ArrayList<Float> floatsX;
    private ArrayList<Float> floatsY;
    private ArrayList<Float> floatsZ;
    private ArrayList<Long> times;
    private SensorData mSensorData;
    private int status=0;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_temperature);
        startBtn = (Button) findComponentById(ResourceTable.Id_start_btn);
        stopBtn = (Button) findComponentById(ResourceTable.Id_stop_btn);
        temperatureData = (Text) findComponentById(ResourceTable.Id_data_temperature);
        startBtn.setClickedListener(this);
        stopBtn.setClickedListener(this);
        initArray();
    }



    private void requestPermissions() {
        if (verifySelfPermission("ohos.hardware.sensor.compass") != IBundleManager.PERMISSION_GRANTED) {
            // 应用未被授予权限
            if (canRequestPermission("ohos.permission.PLACE_CALL")) {
                // 是否可以申请弹框授权(首次申请或者用户未选择禁止且不再提示)
                requestPermissionsFromUser(
                        new String[]{"ohos.permission.GET_TELEPHONY_STATE", "ohos.permission.LOCATION", "ohos.permission.PLACE_CALL"}, 1001);
            } else {
                // 显示应用需要权限的理由，提示用户进入设置授权
            }
        } else {
            // 权限已被授予
            System.out.println("已授权");
        }
    }
    @Override
    public void onClick(Component component) {
        int accessibility = component.getId();
        switch (accessibility){
            case ResourceTable.Id_start_btn:
              startSensor();
                break;
            case ResourceTable.Id_stop_btn:
                if (sensorManager != null) {
                    try {
                        sensorManager.unsubscribeFromSensorData(subscriptionId);
                        status=0;
                    } catch (ESException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }
    private void startSensor(){
        LogUtil.loge("===走了走了");
        try {
            sensorManager = ESSensorManager.getSensorManager(getContext());
            LogUtil.loge("===走了走了"+sensorManager.toString());
            subscriptionId = sensorManager.subscribeToSensorData(SensorUtils.SENSOR_TYPE_MAGNETIC_FIELD, this);
            LogUtil.loge("===走了走了"+subscriptionId);
            status=1;
        } catch (ESException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onStop() {
        super.onStop();
        if (sensorManager != null) {
            try {
                sensorManager.unsubscribeFromSensorData(subscriptionId);
            } catch (ESException e) {
                e.printStackTrace();
            }
        }
    }
    private void initArray() {
        floatsX = new ArrayList<>();
        floatsY = new ArrayList<>();
        floatsZ = new ArrayList<>();
        times = new ArrayList<>();
    }

    @Override
    public void onDataSensed(SensorData data) {
        LogUtil.loge("===走了走了onDataSensed");
        mSensorData = data;
        parseData(mSensorData);

    }

    private void parseData(SensorData data) {
        if(!(data instanceof MagneticFieldData)){
            return;
        }
        MagneticFieldData magneticFieldData = (MagneticFieldData) data;
        long timestamp = magneticFieldData.getTimestamp();

//        String sensorName= "";
        Float getxAxis = magneticFieldData.getxAxis();
        Float getyAxis = magneticFieldData.getyAxis();
        Float getzAxis = magneticFieldData.getzAxis();
//        int sensorType = magneticFieldData.getSensorType();
//        try {
//            sensorName = SensorUtils.getSensorName(sensorType);
//        } catch (ESException e) {
//            e.printStackTrace();
//        }
//       synchronized (senseCompleteNotify){
//           try {
//           while (isGetData) {
//                   senseCompleteNotify.wait(500);
//               if(floatsX.size()==10){
//                   isGetData=false;
//                   showData(sensorName,timestamp);
//               }
//               floatsX.add(getxAxis);
//               floatsY.add(getyAxis);
//               floatsZ.add(getzAxis);
//               times.add(timestamp);
//           }
//           } catch (InterruptedException e) {
//               e.printStackTrace();
//           }
//       }
        StringBuffer xsb = new StringBuffer();
        xsb.append("磁场:\n");
//        xsb.append("dataType:").append(sensorName).append("\n");
        xsb.append("senseStartTimeMillis:").append(timestamp).append("\n");
        Date date = new Date();
        date.setTime(timestamp);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateString = dateFormat.format(date);
        xsb.append("senseStartTime:").append(dateString).append("\n");
        xsb.append("X:").append(getxAxis).append("\n");
        xsb.append("Y:").append(getyAxis).append("\n");
        xsb.append("Z:").append(getzAxis).append("\n");

        getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                temperatureData.setText(xsb.toString());
            }
        });
    }

    private void showData(String sensorName, long timestamp) {
        StringBuffer xsb = new StringBuffer();
        xsb.append("磁场:\n");
        xsb.append("dataType:").append(sensorName).append("\n");
        xsb.append("senseStartTimeMillis:").append(timestamp).append("\n");
        Date date = new Date();
        date.setTime(timestamp);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String dateString = dateFormat.format(date);
        xsb.append("senseStartTime:").append(dateString).append("\n");
        xsb.append("X:[");
        for (int i = 0; i < floatsX.size(); i++) {
            xsb.append(floatsX.get(i)).append(i==floatsX.size()-1?"]":",");
        }
        xsb.append("\nY:[");
        for (int i = 0; i < floatsY.size(); i++) {
            xsb.append(floatsY.get(i)).append(i==floatsY.size()-1?"]":",");
        }
        xsb.append("\nZ:[");
        for (int i = 0; i < floatsZ.size(); i++) {
            xsb.append(floatsZ.get(i)).append(i==floatsZ.size()-1?"]":",");
        }
        xsb.append("\nsensorTimeStamps:[");
        for (int i = 0; i < times.size(); i++) {
            xsb.append(times.get(i)).append(i==times.size()-1?"]":",");
        }
        getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                temperatureData.setText(xsb.toString());
            }
        });
    }

    @Override
    public void onCrossingLowBatteryThreshold(boolean isBelowThreshold) {

    }
    @Override
    public void onRestoreAbilityState(PacMap inState) {
        super.onRestoreAbilityState(inState);
        Optional<Sequenceable> sensorDataOptional = inState.getSequenceable("sensorData");
        int status = inState.getIntValue("status");
        if(sensorDataOptional.isPresent()) {
            mSensorData = (SensorData) sensorDataOptional.get();
            parseData(mSensorData);
            if(status==1){
                startSensor();
            }
        }
    }

    @Override
    public void onSaveAbilityState(PacMap outState) {
        super.onSaveAbilityState(outState);
        if(mSensorData != null) {
            outState.putSequenceableObject("sensorData", mSensorData);
            outState.putIntValue("status",status);
        }
    }
}
